<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据劫持结合发布订阅模式</title>
    <style>
        #main{
            width: 400px;
            height: 400px;
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <div id="main">

    </div>
    <input type="text">
    <script>
        // 定义对象
        var testobj = {username:"zhangsan"}
        // 需要劫持的对象
        var obj = {}
        // 劫持obj对象的name属性，不管你有没有
        Object.defineProperty(obj,'name',{
            get(){
                console.log("访问了get方法");
                return testobj.username
            },
            set(val){
                console.log("访问了set方法",val);
                testobj.username = val;
                document.getElementById("main").innerHTML = obj.name
            }
        })

        document.getElementById("main").innerHTML = obj.name

        // 发布订阅模式
        document.querySelector("input").oninput = function(e){
            console.log(this.value);
            obj.name = this.value;
        }

    </script>
</body>
</html>